package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspqceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.StringBuilders;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspqceService workspqceService;


    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getStatistics(LocalDate begin, LocalDate end) {
        /**开始日期到结束日期的每一天
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        log.info("需要查询的日期:{}",dateList);
        String dateliststr = StringUtils.join(dateList, ",");*/
        List<LocalDate> dateList = getDate(begin, end);
        log.info("需要查询的日期:{}",dateList);
        String dateListstr = StringUtils.join(dateList, ",");
        //计算每一天的营业额
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate localDate:dateList){
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer status = Orders.COMPLETED;
           Double turnover= orderMapper.getDayMoney(beginTime,endTime,status);
           if (turnover==null){
               turnover=0.0;
           }
           turnoverList.add(turnover);
        }

        log.info("查询的日期对应金额:{}",turnoverList);
        String turnoverliststr = StringUtils.join(turnoverList, ",");


        TurnoverReportVO turnoverReportVO=new TurnoverReportVO();
        turnoverReportVO.setDateList(dateListstr);
        turnoverReportVO.setTurnoverList(turnoverliststr);
        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //查询日期范围
        List<LocalDate> dateList = getDate(begin, end);

        //获取新增用户数量,获取总用户数
        List<Integer> newUserList=new ArrayList<>();
        List<Integer>totalUserList=new ArrayList<>();
        for (LocalDate localDate:dateList){
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("end",endTime);
            log.info("截至当天的总人数");
            Integer totalUser=userMapper.getUserCount(map);
            map.put("begin",beginTime);
            log.info("截至当天的新增人数");
            Integer newUser=userMapper.getUserCount(map);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //获取范围日期
        List<LocalDate> dateList = getDate(begin, end);
        //获取每日订单数
        List<Integer>orderCountList=new ArrayList<>();
        List<Integer>validOrderCountList=new ArrayList<>();
        Integer totalOrderSum=0;
        Integer validOrderSum=0;
        for (LocalDate localDate:dateList){
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            //查询每天的订单数
            Integer orderCount=orderMapper.ordersStatistics(map);
            if (orderCount==null){
                orderCount=0;
            }
            //查询每天的有效的订单数
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount=orderMapper.ordersStatistics(map);
            if (validOrderCount==null){
                validOrderCount=0;
            }
            //计算总订单数
            totalOrderSum+=orderCount;
            //计算总有效订单数
            validOrderSum+=validOrderCount;

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //判断总订单是否为0,计算有效订单率
        Double orderCompletionRate =  totalOrderSum!=0? validOrderSum * 1.0 / totalOrderSum:0.0;
        log.info("日期:{},订单总数:{},有效订单数:{},订单总数:{},订单有效总数{},有效率{}",dateList,orderCountList,validOrderCountList,totalOrderSum,validOrderSum,orderCompletionRate);
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderSum)
                .validOrderCount(validOrderSum)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    /**
     * 销量前十
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10food(LocalDate begin, LocalDate end) {
        //获取名称,份数,select od.name,sum(od.number) form orders o , order_detail od where o.id=od.orders_id and o.order_time>=begin and o.order_time<=end and status=#{status} group by od.name  order by sum(od.number) desc limit 0,10;
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //查询数据
        List<GoodsSalesDTO> top10 = orderMapper.getTop10(beginTime, endTime);
        log.info("top10:{}",top10);
        List<String> names = top10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameliststr = StringUtils.join(names, ",");

//        List<Integer> numbers= top10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
//        String numberListstr = StringUtils.join(numbers, ",");
        StringBuilder stringBuilder=new StringBuilder();
        for (GoodsSalesDTO goodsSalesDTO:top10){
            stringBuilder.append(goodsSalesDTO.getNumber()).append(",");
        }
        String numberListstr = stringBuilder.toString();
        int index = numberListstr.lastIndexOf(",");
         numberListstr = numberListstr.substring(0, index);

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(nameliststr)
                .numberList(numberListstr)
                .build();
        return salesTop10ReportVO;
    }

    /**
     * 导出数据
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        //修改起始截至日期
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        //查询数据库
        BusinessDataVO businessDate = workspqceService.getBusinessDate2(beginDate,endDate);
        //读取模板文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //根据模板创建excel文件
            XSSFWorkbook excel=new XSSFWorkbook(resourceAsStream);
            //获取sheet
            XSSFSheet sheet1 = excel.getSheetAt(0);
            //填充时间,获取行,指定单元格
            sheet1.getRow(1).getCell(1).setCellValue("时间:"+beginDate+"-"+endDate);
            //填充营业额
            sheet1.getRow(3).getCell(2).setCellValue(businessDate.getTurnover());
            //填充订单完成率
            sheet1.getRow(3).getCell(4).setCellValue(businessDate.getOrderCompletionRate());
            //填充新增用户数
            sheet1.getRow(3).getCell(6).setCellValue(businessDate.getNewUsers());
            //填充有效订单
            sheet1.getRow(4).getCell(2).setCellValue(businessDate.getValidOrderCount());
            //填充平均客单价格
            sheet1.getRow(4).getCell(4).setCellValue(businessDate.getUnitPrice());
            int row=7;
            //填充明细数据
            for (int i=0;i<30;i++){
                LocalDate localDate=beginDate.plusDays(i);
                //查询某一天营业额
                BusinessDataVO businessDataVO=workspqceService.getBusinessDate2(localDate,localDate);
                //获取指定行
                XSSFRow row1 = sheet1.getRow(row++);
                //填充日期
                row1.getCell(1).setCellValue(localDate.toString());
                //填充营业额
                row1.getCell(2).setCellValue(businessDataVO.getTurnover());
                //填充有效订单
                row1.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                //填充订单完成率
                row1.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                //填充平均客单价格
                row1.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                //填充新增用户数
                row1.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //把文件下载到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     *  获取指定范围的日期
     */
    private List<LocalDate> getDate(LocalDate begin, LocalDate end) {
        //获取日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
         return dateList;
    }
}
